import { UseModalResult } from '@/hooks/useModal'
import { PlusOutlined } from '@ant-design/icons'
import {
  Modal,
  Table,
  Form,
  Input,
  Select,
  Row,
  Col,
  Radio,
  InputNumber,
  Card,
  Button,
  DatePicker,
  Space,
  Empty,
  Tooltip,
} from 'antd'
import './GenerateModal.less'
import { useDetailsColumns } from '../columns'
import { useEffect, useState } from 'react'
import { getSupplierList } from '@/api/supplier'
import dayjs from 'dayjs'
import { validateIsPureDigital, validateVolumeOrWeight } from '@/utils/validator'
interface IProps {
  modalInstance: UseModalResult<any>
  reqestFunction: (...reset: any) => Promise<any>
  openModal: () => void
  addressList: any[]
}
type IOptionType = { label: string; value: string | number; code: string }
const GenerateModal = (props: IProps) => {
  const [SupplierCYOption, setSupplierCYOption] = useState<IOptionType[]>([])
  const [CySuppliercode, setCySuppliercode] = useState('')
  const [getGoodsConfig, setgetGoodsConfig] = useState<Record<string, any>>({})
  const grid = { xs: 24, sm: 24, md: 12, lg: 8, xl: 8, xxl: 8 }
  const gridTwo = { xs: 24, sm: 24, md: 12, lg: 12, xl: 12, xxl: 12 }
  useEffect(() => {
    if (props.modalInstance?.open) {
      if (props.modalInstance.currentRecord?.id) {
        setCySuppliercode(props.modalInstance.currentRecord?.transportSupplierCode)
      }
      props.modalInstance?.form?.setFieldsValue({
        deliveryAddr: '四川省成都市彭州市致和镇致斑路7号（彭州市七色纺内衣产业有限公司）',
        deliveryPerson: '七色纺收货组',
        deliveryPhone: '18482321070',
      })
      getSupplierOptions()
    }
  }, [props.modalInstance.open])

  useEffect(() => {
    if (props.modalInstance.open && props.modalInstance.currentRecord?.id && props?.addressList.length > 0) {
      const { dispatchProvince, dispatchCity, dispatchArea, dispatchAddr, dispatchPerson, dispatchPhone } =
        props.modalInstance.currentRecord
      setgetGoodsConfig({
        province: dispatchProvince,
        city: dispatchCity,
        area: dispatchArea,
        address: dispatchAddr,
      })
      console.log(props?.addressList, 'props?.addressList')

      const selectedItem = props?.addressList?.find(
        (item) =>
          item.province == dispatchProvince &&
          item.city == dispatchCity &&
          item.area == dispatchArea &&
          item.address == dispatchAddr &&
          item.contacts == dispatchPerson &&
          item.phone == dispatchPhone,
      )
      console.log(selectedItem, 'selectedItem')

      if (selectedItem) {
        props.modalInstance?.form.setFieldsValue({
          dispatchAddressId: selectedItem?.id || null,
        })
      }
    }
  }, [props.modalInstance.open, props.addressList])

  useEffect(() => {
    if (!props.modalInstance.currentRecord?.id) {
      const num = props.modalInstance?.currentRecord?.dataSource?.reduce(
        (pre: number, current: any) => pre + (Number(current?.totalBoxQty) || 0),
        0,
      )
      props?.modalInstance?.form?.setFieldValue('boxQty', num)
    }
  }, [props.modalInstance.open, props.modalInstance?.currentRecord?.dataSource])
  const getSupplierOptions = async () => {
    const res = await getSupplierList<{ supplierName: string; supplierId: string; supplierCode: string }>({
      supplierClassificationCode: '承运商',
      keyword: '德邦',
      useStatus: 1,
      // 0 不鉴权
      authSupplier: 0,
    })
    if (res.code === 200) {
      const SupplierCYOption =
        res?.data?.list?.map((item) => {
          return {
            label: item.supplierName,
            value: item.supplierId,
            code: item.supplierCode,
          }
        }) || []
      setSupplierCYOption(SupplierCYOption)
      if (!props.modalInstance.currentRecord?.id && SupplierCYOption && SupplierCYOption.length > 0) {
        props?.modalInstance?.form?.setFieldValue('transportSupplierId', SupplierCYOption[0]?.value)
        setCySuppliercode(SupplierCYOption[0]?.code)
      }
    }
  }
  return (
    <Modal
      width={1400}
      title="发起物流需求单"
      wrapClassName="custom_generate_modal_wrap"
      maskClosable={false}
      footer={props.modalInstance.currentRecord?.transportStatus ? null : undefined}
      centered
      open={props.modalInstance.open}
      onCancel={props.modalInstance.closeModal}
      onOk={() => {
        props.modalInstance.handleSubmit((vals) => {
          return props.reqestFunction({
            ...vals,
            deliveryTime: vals.deliveryTime ? dayjs(vals.deliveryTime).format('YYYY-MM-DD HH:mm:ss') : null,
            dispatchTime: vals.dispatchTime ? dayjs(vals.dispatchTime).format('YYYY-MM-DD HH:mm:ss') : null,
            orderSupplierId: props.modalInstance.currentRecord?.dataSource[0]?.supplierId,
            orderSupplierCode: props.modalInstance.currentRecord?.dataSource[0]?.supplierCode,
            transportSupplierCode: CySuppliercode,
            reserveInvoiceCodeList:
              props.modalInstance.currentRecord?.dataSource?.map((item: any) => item.reserveInvoiceCode) || [],
            dispatchProvince: getGoodsConfig?.province,
            dispatchCity: getGoodsConfig?.city,
            dispatchArea: getGoodsConfig?.area,
            dispatchAddr: getGoodsConfig?.address,
            deliveryProvince: '四川省',
            deliveryCity: '成都市',
            deliveryArea: '彭州市',
            id: props.modalInstance.currentRecord?.id || null,
          })
        })
      }}
      confirmLoading={props.modalInstance.confirmLoading}
    >
      <div className="generatemodal_main_wrap">
        <div className="delivery_details">
          <div className="delivery_details-title">发货明细</div>
          <Table
            size="small"
            bordered
            columns={useDetailsColumns()}
            dataSource={props.modalInstance.currentRecord?.dataSource || []}
            rowKey="reserveInvoiceCode"
            scroll={{ x: 800, y: 200 }}
            pagination={false}
            rowHoverable={false}
            rowClassName={(_, index) => {
              return index % 2 === 0 ? '' : 'zebra-row-odd'
            }}
          />
        </div>
        <div className="logistics_demand">
          <div className="logistics_demand-title">物流需求</div>
          <div className="logistics_demand-form">
            <Form
              form={props.modalInstance?.form}
              layout="inline"
              labelAlign="left"
              labelWrap
              initialValues={{
                transportType: 0,
              }}
              disabled={!!props.modalInstance.currentRecord?.transportStatus}
            >
              <Row gutter={[20, 20]} style={{ marginBottom: 12 }}>
                <Col {...grid}>
                  <Form.Item label="需求方">
                    {props.modalInstance.currentRecord?.dataSource[0]?.supplierName || '-'}
                  </Form.Item>
                </Col>
                <Col {...grid}>
                  <Form.Item
                    label="承运商"
                    name="transportSupplierId"
                    rules={[{ required: true, message: '请选择承运商' }]}
                  >
                    <Select
                      allowClear
                      style={{ width: 300 }}
                      options={SupplierCYOption}
                      placeholder="请选择承运商"
                      onChange={(_, items: any) => {
                        setCySuppliercode(items?.code)
                      }}
                    ></Select>
                  </Form.Item>
                </Col>
                <Col {...grid}>
                  <Form.Item
                    label="运输方式"
                    name="transportType"
                    rules={[{ required: true, message: '请选择运输方式' }]}
                  >
                    <Radio.Group
                      options={[
                        { label: '零担', value: 0 },
                        { label: '包车', value: 1 },
                      ]}
                      onChange={(event) => {
                        // 提货时间在今天19点前(含19点) 整车+2天 零担+3天 提货时间在今天19点后 整车+3天 零担+4天
                        const transportType = event?.target.value
                        const dispatchTime = props.modalInstance.form?.getFieldValue('dispatchTime')
                        const isAfterAt19 = dayjs(dispatchTime).hour() > 18
                        const addDays = isAfterAt19 ? (transportType == 0 ? 4 : 3) : transportType == 0 ? 3 : 2
                        const deliveryTime = dayjs(dispatchTime).add(addDays, 'day')
                        props.modalInstance.form.setFieldValue('deliveryTime', deliveryTime)
                      }}
                    ></Radio.Group>
                  </Form.Item>
                </Col>
                <Col {...grid}>
                  <div style={{ display: 'flex', alignItems: 'flex-end', gap: 6, flexWrap: 'nowrap' }}>
                    <Form.Item label="箱包数" name="boxQty" rules={[{ required: true, message: '请输入箱包数' }]}>
                      <InputNumber
                        placeholder="请输入箱包数"
                        precision={0}
                        min={0}
                        addonAfter="箱"
                        style={{ width: 250 }}
                      ></InputNumber>
                    </Form.Item>
                    <span>
                      参考值：
                      {props.modalInstance.currentRecord?.dataSource?.reduce(
                        (pre: number, current: any) => pre + (Number(current?.totalBoxQty) || 0),
                        0,
                      )}
                    </span>
                  </div>
                </Col>
                <Col {...grid}>
                  <Form.Item
                    label="方数(m³)"
                    name="volume"
                    rules={[{ validator: () => validateVolumeOrWeight(props.modalInstance?.form) }]}
                  >
                    <InputNumber
                      placeholder="请输入方数"
                      precision={4}
                      min={0}
                      addonAfter="m³"
                      style={{ width: 300 }}
                    ></InputNumber>
                  </Form.Item>
                </Col>
                <Col {...grid}>
                  <Form.Item
                    label="重量(kg)"
                    name="weight"
                    rules={[{ validator: () => validateVolumeOrWeight(props.modalInstance?.form) }]}
                  >
                    <InputNumber
                      placeholder="请输入重量"
                      precision={2}
                      min={0}
                      addonAfter="kg"
                      style={{ width: 300 }}
                    ></InputNumber>
                  </Form.Item>
                </Col>
                <Col {...grid}>
                  <Form.Item label="物流备注" name="remark">
                    <Input.TextArea placeholder="请输入物流备注" rows={3} showCount maxLength={600}></Input.TextArea>
                  </Form.Item>
                </Col>
              </Row>
            </Form>
          </div>
        </div>
        <div className="card_box">
          <div className="card_item">
            <Card
              title="提货信息"
              extra={
                <Button
                  type="dashed"
                  icon={<PlusOutlined />}
                  onClick={() => {
                    props.openModal()
                  }}
                  disabled={!!props.modalInstance.currentRecord?.transportStatus}
                >
                  配置提货地址
                </Button>
              }
            >
              <Form
                form={props.modalInstance.form}
                layout="inline"
                labelAlign="left"
                labelWrap
                initialValues={{ transportType: 0 }}
                disabled={!!props.modalInstance.currentRecord?.transportStatus}
              >
                <Row gutter={[20, 20]} style={{ marginBottom: 12 }}>
                  <Col {...gridTwo}>
                    <Form.Item
                      label="提货时间"
                      name="dispatchTime"
                      rules={[{ required: true, message: '请选择提货时间' }]}
                    >
                      <DatePicker
                        style={{ width: 280 }}
                        showTime
                        placeholder="请选择提货时间"
                        onChange={(val) => {
                          // 提货时间在今天19点前(含19点) 整车+2天 零担+3天 提货时间在今天19点后 整车+3天 零担+4天
                          const isAfterAt19 = dayjs(val).hour() > 18
                          const transportType = props.modalInstance.form?.getFieldValue('transportType')
                          const addDays = isAfterAt19 ? (transportType == 0 ? 4 : 3) : transportType == 0 ? 3 : 2
                          const deliveryTime = dayjs(val).add(addDays, 'day')
                          props.modalInstance.form.setFieldValue('deliveryTime', deliveryTime)
                        }}
                      ></DatePicker>
                    </Form.Item>
                  </Col>
                  <Col {...gridTwo}>
                    <Form.Item
                      label="提货地址"
                      name="dispatchAddressId"
                      rules={[{ required: true, message: '请选择提货地址' }]}
                    >
                      <Select
                        allowClear
                        options={
                          props?.addressList?.map((item) => {
                            return {
                              ...item,
                              label: (
                                <Space>
                                  <span>
                                    {item?.province}
                                    {item?.city}
                                    {item?.area}
                                  </span>
                                  <span>{item?.address}</span>
                                </Space>
                              ),
                              value: item.id,
                            }
                          }) || []
                        }
                        placeholder="请选择提货地址"
                        style={{ width: 280 }}
                        notFoundContent={<Empty description="请配置提货地址" image={Empty.PRESENTED_IMAGE_SIMPLE} />}
                        onChange={(_, items: any) => {
                          props.modalInstance.form?.setFieldsValue({
                            dispatchPerson: items?.contacts || null,
                            dispatchPhone: items?.phone || null,
                          })
                          setgetGoodsConfig({ ...items })
                        }}
                        optionRender={(options) => {
                          const item = options?.data
                          const content = (
                            <Space>
                              <span>{item?.contacts}</span>
                              <span>{item?.phone}</span>
                              <span>
                                {item?.province}
                                {item?.city}
                                {item?.area}
                              </span>
                              <span>{item?.address}</span>
                            </Space>
                          )
                          return (
                            <Tooltip title={content} overlayInnerStyle={{ width: 'max-content' }}>
                              <div>{content}</div>
                            </Tooltip>
                          )
                        }}
                      ></Select>
                    </Form.Item>
                  </Col>
                  <Col {...gridTwo}>
                    <Form.Item label="提货联系人">
                      <Space.Compact>
                        <Form.Item
                          noStyle
                          label="提货联系人"
                          name="dispatchPerson"
                          rules={[
                            {
                              required: true,
                              message: '请输入提货联系人',
                            },
                          ]}
                        >
                          <Input style={{ width: '40%' }} placeholder="联系人" disabled />
                        </Form.Item>
                        <Form.Item
                          noStyle
                          label="提货联系人电话"
                          name="dispatchPhone"
                          rules={[
                            {
                              required: true,
                              message: '请输入提货联系人电话',
                            },
                            { validator: validateIsPureDigital },
                          ]}
                        >
                          <Input style={{ width: '60%' }} placeholder="联系人电话" disabled />
                        </Form.Item>
                      </Space.Compact>
                    </Form.Item>
                  </Col>
                </Row>
              </Form>
            </Card>
          </div>
          <div className="card_item">
            <Card title="送货信息">
              <Form
                form={props.modalInstance.form}
                layout="inline"
                labelAlign="left"
                labelWrap
                initialValues={{ transportType: 0 }}
                disabled={!!props.modalInstance.currentRecord?.transportStatus}
              >
                <Row gutter={[20, 20]} style={{ marginBottom: 12 }}>
                  <Col {...gridTwo}>
                    <Form.Item
                      label="送货时间"
                      name="deliveryTime"
                      rules={[{ required: true, message: '请选择送货时间' }]}
                    >
                      <DatePicker style={{ width: 280 }} showTime placeholder="请选择送货时间" disabled></DatePicker>
                    </Form.Item>
                  </Col>
                  <Col {...gridTwo}>
                    <Form.Item
                      label="送货地址"
                      name="deliveryAddr"
                      rules={[{ required: true, message: '请输入送货地址' }]}
                    >
                      <Input placeholder="请选择送货地址" style={{ width: 280 }} disabled></Input>
                    </Form.Item>
                  </Col>
                  <Col {...gridTwo}>
                    <Form.Item label="送货联系人">
                      <Space.Compact>
                        <Form.Item
                          noStyle
                          label="送货联系人"
                          name="deliveryPerson"
                          rules={[
                            {
                              required: true,
                              message: '请输入送货联系人',
                            },
                          ]}
                        >
                          <Input style={{ width: '40%' }} placeholder="联系人" disabled />
                        </Form.Item>
                        <Form.Item
                          noStyle
                          label="送货联系人电话"
                          name="deliveryPhone"
                          rules={[
                            {
                              required: true,
                              message: '请输入送货联系人电话',
                            },
                          ]}
                        >
                          <Input style={{ width: '60%' }} placeholder="联系人电话" disabled />
                        </Form.Item>
                      </Space.Compact>
                    </Form.Item>
                  </Col>
                </Row>
              </Form>
            </Card>
          </div>
        </div>
      </div>
    </Modal>
  )
}
export default GenerateModal
